package com.sgcc.pda.mdrh.task.safe.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.component.service.PluginServiceClient;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.greendao.entity.AppBaseInfo;
import com.sgcc.pda.mdrh.zoom.plugin.InnerPluginUtil;
import com.sgcc.pda.mdrh.zoom.plugin.PluginAsyncTask;

import java.util.List;

import static com.sgcc.pda.mdrh.zoom.plugin.InnerPluginUtil.APP_ALIAS_FACE;

/**
 * 描述：插件服务
 * 作者：jianiuqi 2020-09-25 15:21
 */
public class PluginService extends Service {

    /**
     * 定义必装应用检测未安装的集合
     */
    private List<AppBaseInfo> mListNeedInstallApp;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.e("插件安装服务启动成功");
        bindData();
        // 遍历安装assets中的基础服务插件
        for (int i = 0; i < mListNeedInstallApp.size(); i++) {
            AppBaseInfo item = mListNeedInstallApp.get(i);
            if (item != null) {
                String assetsPath = item.getAssetsPath();
                installAssets(assetsPath);
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 安装assets插件和gis原生app
     *
     * @param assetsPath assets路径
     */
    private void installAssets(String assetsPath) {
        PluginAsyncTask.installAssets(this, assetsPath, new PluginAsyncTask.ResultListener() {
            @Override
            public void onFinish(String name) {
                if (!TextUtils.isEmpty(name)) {
                    for (AppBaseInfo info : mListNeedInstallApp) {
                        if (TextUtils.equals(name, info.getAppAlias())) {
                            mListNeedInstallApp.remove(info);
                            if (mListNeedInstallApp.size() == 0) {
                                bindData();
                            }
                            break;
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取所有未安装应用列表
     */
    private void bindData() {
        mListNeedInstallApp = InnerPluginUtil.getUninstallList(this);
        LogUtil.i("需安装列表是否为空：" + mListNeedInstallApp.isEmpty());
        if (mListNeedInstallApp.isEmpty()) {
            LogUtil.e("插件安装成功");
            //启动人脸识别插件初始化服务
            PluginServiceClient.startService(this, RePlugin.createIntent(APP_ALIAS_FACE,
                    "com.sgcc.pda.faceplugin.service.FaceLoadService"));
        }
    }
}
